#target "indesign"
(function () {
    if (app.documents.length === 0) { alert("请先打开一个文档。"); return; }
    var doc = app.activeDocument;

    // ===================== 复用/改写自 ChainGREP 的工具函数 =====================

    // 返回脚本所在目录（ChainGREP 用于写文件；这里仅为兼容保留）
    function getScriptFolderPath() {
        var skriptPath;
        try {
            $.level = 0;
            skriptPath = app.activeScript.parent;
        } catch (e) {
            $.level = 2;
            skriptPath = File(e.fileName).parent;
        }
        return skriptPath;
    }

    // 扫描查询目录并解析 XML，返回 fcQueryArray
    // fcQueryObject: {name, type:"GREP", findWhat, changeTo, findPStyle, findCStyle, changePStyle, changeCStyle}
    function parseQueries(folderType) {
        var fcQueryArray = [];
        var fcFolder;
        var platfrom = File.fs;

        // 用户目录
        if (platfrom == "Macintosh") {
            fcFolder = File(app.scriptPreferences.scriptsFolder.parent.parent + "/Find-Change Queries/" + folderType);
        } else {
            fcFolder = Folder(app.scriptPreferences.scriptsFolder.parent.parent + "/Find-Change Queries/" + folderType);
        }
        fcQueryArray = readFolder(fcFolder, fcQueryArray);

        // 应用程序预设目录（带本地化子目录）
        if (platfrom == "Macintosh") {
            fcFolder = File(Folder.appPackage.parent + "/Presets/Find-Change Queries/" + folderType + "/" + $.locale);
        } else {
            fcFolder = File(Folder.appPackage + "/Presets/Find-Change Queries/" + folderType + "/" + $.locale);
        }
        fcQueryArray = readFolder(fcFolder, fcQueryArray);

        return fcQueryArray;
    }

    // 读取某目录下的 *.xml 并解析为 fcQueryArray（改写自 ChainGREP）
    function readFolder(fcFolder, fcQueryArray) {
        if (fcFolder.exists) {
            var files = fcFolder.getFiles("*.xml");
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                file.encoding = "UTF-8";
                file.open("r");
                var searchXML;
                try {
                    searchXML = XML(file.read());
                } catch (e) {
                    alert("无法读取 XML 文件:\n" + decodeURI(file) + "\n若它不是 FindChange 查询，请从该目录移除。");
                    try { file.close(); } catch (_) {}
                    continue;
                }
                file.close();

                var findWhat = String(searchXML.xpath("/Query/Description/FindExpression/@value"));
                var changeTo = String(searchXML.xpath("/Query/Description/ReplaceExpression/@value"));
                var findPStyle = String(searchXML.xpath("/Query/Description/FindFormatSettings/TextAttribute[@type='pstyle']/@value"));
                var findCStyle = String(searchXML.xpath("/Query/Description/FindFormatSettings/TextAttribute[@type='cstyle']/@value"));
                var changePStyle = String(searchXML.xpath("/Query/Description/ReplaceFormatSettings/TextAttribute[@type='pstyle']/@value"));
                var changeCStyle = String(searchXML.xpath("/Query/Description/ReplaceFormatSettings/TextAttribute[@type='cstyle']/@value"));

                var fcQueryObject = {
                    name: file.displayName.replace(/\.xml$/, ""),
                    type: "GREP",
                    findWhat: findWhat,
                    changeTo: changeTo,
                    findPStyle: findPStyle,
                    findCStyle: findCStyle,
                    changePStyle: changePStyle,
                    changeCStyle: changeCStyle
                };
                fcQueryArray.push(fcQueryObject);
            }
        } else {
            // 不中断，仅提示
            // alert("未能读取查询目录：\n" + decodeURI(fcFolder));
        }
        return fcQueryArray;
    }

    // 从“样式路径”获得样式对象（完全沿用 ChainGREP 的逻辑）
    function getStyleByString(docOrGroup, string, property) {
        if (string == "[No character style]") return docOrGroup[property][0];
        if (string == "[No paragraph style]") return docOrGroup[property][0];
        if (string == "NormalParagraphStyle") return docOrGroup[property][1];
        var stringResult = String(string).match(/^(.*?[^\\]):(.*)$/);
        var styleName = (stringResult) ? stringResult[1] : string;
        styleName = styleName.replace(/\\:/g, ':');
        var remainingString = (stringResult) ? stringResult[2] : '';
        var newProperty = (stringResult) ? property.replace(/s$/, '') + 'Groups' : property;
        var styleOrGroup = docOrGroup[newProperty].itemByName(styleName);
        if (remainingString.length > 0 && styleOrGroup.isValid) {
            styleOrGroup = getStyleByString(styleOrGroup, remainingString, property);
        }
        return styleOrGroup;
    }

    // 文本缩略显示
    function shorten(s, maxLen) {
        s = (s == null) ? "" : String(s);
        var m = maxLen || 80;
        if (s.length > m) return s.substring(0, m - 1) + "…";
        return s;
    }

    // ===================== 读取所有 GREP 预设 =====================
    var fcQueryArray = parseQueries("GREP");
    if (!fcQueryArray || fcQueryArray.length === 0) {
        alert("没有找到任何已保存的 GREP 查询。\n请先在“查找/更改 > GREP”中保存一个查询。");
        return;
    }

    // 排序（与 ChainGREP 一致）
    fcQueryArray.sort(function (a, b) {
        var A = a.name.toUpperCase(), B = b.name.toUpperCase();
        if (A < B) return -1;
        if (A > B) return 1;
        return 0;
    });

    // ===================== 按 ChainGREP 风格创建交互 UI（单选） =====================
    var w = new Window("dialog", "选择 GREP 预设以删除匹配文本框");
    w.orientation = "column";
    var lbPanel = w.add("panel", undefined, "已保存的 GREP 预设");
    lbPanel.alignment = ["fill", "fill"];
    lbPanel.margins = [10, 20, 10, 10];

    var list = lbPanel.add("listbox", undefined, undefined, {
        numberOfColumns: 4,
        showHeaders: true,
        columnTitles: ["Find/Change Query", "Type", "Find", "Change"],
        multiselect: false,
        columnWidths: [260, 60, 240, 240]
    });
    list.alignment = ["fill", "fill"];
    list.preferredSize.height = 380;
    list.preferredSize.width = 820;

    // 填充
    for (var i = 0; i < fcQueryArray.length; i++) {
        var q = fcQueryArray[i];
        var lItem = list.add("item", q.name);
        lItem.fcQuery = q;
        lItem.helpTip = "Find: " + q.findWhat + "\rChange: " + q.changeTo;
        lItem.subItems[0].text = q.type;
        lItem.subItems[1].text = shorten(q.findWhat, 120);
        lItem.subItems[2].text = shorten(q.changeTo, 120);
    }
    list.selection = 0;

    var uiCtrlGroup = w.add("group");
    uiCtrlGroup.orientation = "row";
    uiCtrlGroup.alignment = "right";
    var cancelBtn = uiCtrlGroup.add("button", undefined, "Cancel");
    var okButton = uiCtrlGroup.add("button", undefined, "OK");

    cancelBtn.onClick = function () { w.close(0); };
    okButton.onClick = function () {
        if (!list.selection) { alert("请先选择一个 GREP 预设。"); return; }
        w.close(1);
    };

    if (w.show() !== 1) { w.close(); return; }
    var chosen = list.selection.fcQuery;
    w.close();

    // ===================== 设置查找条件（直接使用 XML 内容） =====================
    // 备份现场
    var savedFind = app.findGrepPreferences.properties;
    var savedChange = app.changeGrepPreferences.properties;
    var savedOpts = app.findChangeGrepOptions.properties;

    // 清空
    app.findGrepPreferences = NothingEnum.NOTHING;
    app.changeGrepPreferences = NothingEnum.NOTHING;

    // 设定 find / change 字段
    app.findGrepPreferences.findWhat = chosen.findWhat || "";
    app.changeGrepPreferences.changeTo = chosen.changeTo || "";

    // 套用样式（若 XML 中有保存）
    try {
        if (chosen.findCStyle) {
            var fcs = getStyleByString(doc, chosen.findCStyle, 'characterStyles');
            if (fcs && fcs.isValid) app.findGrepPreferences.appliedCharacterStyle = fcs;
        }
        if (chosen.findPStyle) {
            var fps = getStyleByString(doc, chosen.findPStyle, 'paragraphStyles');
            if (fps && fps.isValid) app.findGrepPreferences.appliedParagraphStyle = fps;
        }
        if (chosen.changeCStyle) {
            var ccs = getStyleByString(doc, chosen.changeCStyle, 'characterStyles');
            if (ccs && ccs.isValid) app.changeGrepPreferences.appliedCharacterStyle = ccs;
        }
        if (chosen.changePStyle) {
            var cps = getStyleByString(doc, chosen.changePStyle, 'paragraphStyles');
            if (cps && cps.isValid) app.changeGrepPreferences.appliedParagraphStyle = cps;
        }
    } catch (e) {
        // 样式缺失时不阻断，仅忽略样式应用
    }

    // ===================== 执行查找并删除承载匹配文本的文本框 =====================
    var results;
    try {
        results = doc.findGrep();
    } catch (e2) {
        alert("执行查找时出错：\n" + e2);
        // 恢复
        try {
            app.findGrepPreferences.properties = savedFind;
            app.changeGrepPreferences.properties = savedChange;
            app.findChangeGrepOptions.properties = savedOpts;
        } catch (_) {}
        return;
    }

    // 收集承载匹配文本的 TextFrame（去重）
    var frameMap = {};
    var frames = [];
    for (var r = 0; r < results.length; r++) {
        var it = results[r];
        if (!it || !it.isValid) continue;
        var pfs = it.parentTextFrames;
        if (!pfs || pfs.length === 0) continue; // overset 中无实际文本框，略过
        for (var j = 0; j < pfs.length; j++) {
            var tf = pfs[j];
            if (!tf || !tf.isValid) continue;
            if (!(tf instanceof TextFrame)) continue;
            var id = tf.id;
            if (!frameMap[id]) { frameMap[id] = true; frames.push(tf); }
        }
    }

    if (frames.length === 0) {
        alert("没有找到包含匹配文本的文本框。");
        // 恢复
        try {
            app.findGrepPreferences.properties = savedFind;
            app.changeGrepPreferences.properties = savedChange;
            app.findChangeGrepOptions.properties = savedOpts;
        } catch (_) {}
        return;
    }

    if (!confirm("将删除 " + frames.length + " 个文本框（含锚定文本框）。\n是否继续？")) {
        try {
            app.findGrepPreferences.properties = savedFind;
            app.changeGrepPreferences.properties = savedChange;
            app.findChangeGrepOptions.properties = savedOpts;
        } catch (_) {}
        return;
    }

    var deleted = 0, skippedLocked = 0, errored = 0;
    app.doScript(function () {
        for (var k = 0; k < frames.length; k++) {
            var f = frames[k];
            try {
                if (!f.isValid) continue;
                if (f.locked || (f.itemLayer && f.itemLayer.locked)) { skippedLocked++; continue; }
                f.remove();
                deleted++;
            } catch (ex) { errored++; }
        }
    }, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "删除匹配 GREP 的文本框");

    // 恢复查找设置
    try {
        app.findGrepPreferences.properties = savedFind;
        app.changeGrepPreferences.properties = savedChange;
        app.findChangeGrepOptions.properties = savedOpts;
    } catch (_) {}

    alert("完成：已删除文本框 " + deleted + " 个；跳过（锁定/锁层） " + skippedLocked + " 个；出错 " + errored + " 个。");
})();
